// 基本信息
import DialogBox from "@/components/DialogBox";
import { ElForm, ElTooltip } from "element-plus";
import { getCurrentInstance, defineComponent, ComponentInternalInstance } from "vue";
import LazyUploadFile from "@/components/Upload/LazyUploadFile.vue";
import { showMsg, showTips } from "@/utils/util";
import { useRoute } from "vue-router";
import { serviceAdd, serviceMod } from "@/api/modules/service/service";
import { SvcType } from "@/enums/statusEnum";
import { Dict, DictType, getDictList } from "@/utils/cacheUtil";
import { ResultEnum } from "@/enums/httpEnum";
import { MessageType } from "@/enums/messageEnum";

export default defineComponent({
	props: {
		width: String,
		title: String,
		appId: String,
		nodeSn: String,
		detail: {
			type: Object,
			default() {
				return {};
			}
		}
	},
	emits: ["submit"],
	setup(props, { attrs, emit }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		const formRule = reactive({
			name: [{ required: true, message: proxy?.$t("servicedialog.form_rule.name"), trigger: "change" }],
			key: [{ required: true, message: proxy?.$t("servicedialog.form_rule.key"), trigger: "change" }]
			// architecture: [{ required: true, message: "应用运行系统不能为空", trigger: "change" }]
		});

		watch(
			() => props.detail,
			() => {
				initArchPath();
			}
		);

		const validData = () => {
			formRef.value?.validate(async valid => {
				if (valid) {
					console.log(props.detail);
					let api = props.detail.id ? serviceMod : serviceAdd;
					//web模式没有启动参数
					props.detail.arg = props.detail.svcType == "web" ? "" : props.detail.arg;
					let { code, result, message } = await api({
						...props.detail,
						appId: props.appId
						// appInstanceKey: props.nodeSn ? props.detail.appInstanceId.split(".")[0] : ""
					});

					//操作失败
					if (code != ResultEnum.SUCCESS) {
						showMsg(message, MessageType.error);
						return;
					}
					showTips(code, props.detail.id ? "更新服务" : "添加服务");
					//直接提交表单
					if (!uploadEl.value.length) {
						props.detail.id = result;
						upView.value = [];
						emit("submit", props.detail);
					} else {
						typeList.value.map((item, index) => {
							if (uploadEl.value[index] && uploadEl.value[index].getFile()) {
								uploadEl.value[index]["submit"]({ id: result, architecture: item.key });
								upView.value.push(item.key);
							}
						});
						if (upView.value.length == 0) {
							emit("submit", props.detail);
						}
					}
				}
			});
		};
		const options = ref(SvcType);
		const uploadEl = ref<any>([]);
		const upView = ref<any>([]);
		const uploadSuccess = (e: any) => {
			if (e.success) {
				upView.value = upView.value.filter((item: any) => {
					return !e.result.path.includes(item);
				});
			} else {
				showTips(e.code, "上传", e.message);
			}
			if (upView.value.length == 0) {
				emit("submit", props.detail);
			}
		};
		const svcTypeChange = () => {
			props.detail.arg = props.detail.svcType == "docker" ? `-net host -v data:/home/${route.query.key}/data` : "";
		};
		const typeList = ref<Dict[]>([]);
		getDictList(DictType.AppletPlatform).then(list => {
			typeList.value = list;
		});
		const fileArchPath = ref<any>({});
		const initArchPath = () => {
			props.detail.path = props.detail.path || {};
			typeList.value.map(dict => {
				if (props.detail.path[dict.key]) {
					props.detail.path[dict.key] = `${props.detail.path[dict.key]}${
						props.detail.svcType != "docker"
							? props.detail.path[dict.key].split("/").at(-1) == props.detail.key
								? ""
								: `/${props.detail.key}`
							: ""
					}`;
				} else {
					props.detail.path[dict.key] = "";
				}
			});
			fileArchPath.value = JSON.parse(JSON.stringify(props.detail.path));
		};
		return () => {
			return (
				<DialogBox {...attrs} width={props.width} title={props.title} onConfirm={() => validData()}>
					<div class="flex-col">
						<div class="flex-1">
							<el-form model={props.detail} ref={formRef} rules={formRule} label-width="120px">
								<el-form-item label={proxy?.$t("servicedialog.form_label.name")} prop="name">
									<el-input
										v-model={props.detail.name}
										placeholder={proxy?.$t("servicedialog.placeholder.name")}
										disabled={!!props.nodeSn}
									/>
								</el-form-item>
								<el-form-item label={proxy?.$t("servicedialog.form_label.key")} prop="key">
									<el-input
										v-model={props.detail.key}
										placeholder={proxy?.$t("servicedialog.placeholder.key")}
										disabled={!!props.detail.id}
									/>
								</el-form-item>

								<el-form-item label={proxy?.$t("servicedialog.form_label.svc_type")} prop="svcType">
									<el-select
										v-model={props.detail.svcType}
										placeholder={proxy?.$t("servicedialog.placeholder.svc_type")}
										class="w-full"
										disabled={!!props.detail.id}
										onChange={svcTypeChange}
									>
										{options.value.map((item: any) => {
											return <el-option key={item.value} label={item.label} value={item.value}></el-option>;
										})}
									</el-select>
								</el-form-item>
								{props.detail.svcType == "docker" ? (
									<>
										<el-form-item label={proxy?.$t("servicedialog.form_label.docker")} prop="bin">
											<el-input
												value={`${props.detail.key || ""}.${route.query.key || ""}`}
												placeholder={proxy?.$t("servicedialog.placeholder.docker")}
												disabled
											/>
										</el-form-item>
										{typeList.value.map((dict: Dict) => {
											return (
												<el-form-item label={dict.label}>
													<el-input
														v-model={props.detail.path[dict.key]}
														placeholder={proxy?.$t("servicedialog.placeholder.address")}
														disabled={!!props.nodeSn}
													/>
												</el-form-item>
											);
										})}
									</>
								) : (
									typeList.value.map((dict: Dict, index) => {
										return (
											<el-form-item
												prop="bin"
												v-slots={{
													label: () => {
														return (
															<div>
																{dict.label}
																{props.detail.svcType == "web" && (
																	<ElTooltip
																		raw-content
																		v-slots={{
																			content: () => {
																				return <div class="title">{proxy?.$t("servicedialog.tooltip.content")}</div>;
																			}
																		}}
																	>
																		<i class="iconfont iconhelp-circle pl-2 "></i>
																	</ElTooltip>
																)}
															</div>
														);
													}
												}}
											>
												<div class="form-item-upload">
													{fileArchPath.value && JSON.stringify(fileArchPath.value) != "{}" && fileArchPath.value[dict.key] ? (
														<div class="file-info ">
															{fileArchPath.value[dict.key]}
															<el-link
																type="primary"
																class="delete-server-file ml-2 leading-3"
																onClick={() => (fileArchPath.value[dict.key] = "")}
																disabled={!!props.nodeSn}
															>
																{proxy?.$t("servicedialog.link.reupload")}
															</el-link>
														</div>
													) : null}
													<LazyUploadFile
														style={{ display: fileArchPath.value[dict.key] ? "none" : "block" }}
														title={!props.detail.id ? "请输入服务名称" : "点击选服务程序"}
														ref={el => (uploadEl.value[index] = el)}
														showIcon={false}
														disabled={!props.detail.name || !!props.nodeSn}
														v-model:fileUrl={fileArchPath.value[dict.key]}
														v-model:fileName={fileArchPath.value[dict.key]}
														onSuccess={uploadSuccess}
														width="150px"
														height="32px"
														emptyTips={`${proxy?.$t("servicedialog.uploadfile.emptytips1")}${
															props.detail.svcType == "web"
																? proxy?.$t("servicedialog.uploadfile.emptytips2")
																: proxy?.$t("servicedialog.uploadfile.emptytips3")
														}`}
													></LazyUploadFile>
												</div>
											</el-form-item>
										);
									})
								)}
								{(props.detail.svcType == "bin" || props.detail.svcType == "docker") && (
									<el-form-item label={proxy?.$t("servicedialog.form_label.arg")} prop="arg">
										<el-input v-model={props.detail.arg} placeholder={proxy?.$t("servicedialog.placeholder.arg")} />
									</el-form-item>
								)}
								{/* {(props.detail.svcType == "bin" || props.detail.svcType == "web") && (
										<el-form-item
											label="服务程序"
											prop="bin"
											v-slots={{
												label: () => {
													return (
														<div>
															{props.detail.svcType == "web" ? "web资源" : "服务程序"}
															{props.detail.svcType == "web" && (
																<ElTooltip
																	raw-content
																	v-slots={{
																		content: () => {
																			return <div class="title">上传文件必须是zip包</div>;
																		}
																	}}
																>
																	<i class="iconfont iconhelp-circle pl-2 "></i>
																</ElTooltip>
															)}
														</div>
													);
												}
											}}
										>
											<div class="form-item-upload">
												{props.detail.bin ? (
													<div class="file-info ">
														{props.detail.bin}
														<el-link
															type="primary"
															class="delete-server-file ml-2 leading-3"
															onClick={() => (props.detail.bin = "")}
														>
															重新上传
														</el-link>
													</div>
												) : null}
												<LazyUploadFile
													style={{ display: props.detail.bin ? "none" : "block" }}
													title={!props.detail.id ? "请输入服务名称" : "点击选服务程序"}
													ref={uploadEl}
													showIcon={false}
													disabled={!props.detail.name}
													v-model:fileUrl={props.detail.bin}
													v-model:fileName={props.detail.bin}
													onSuccess={uploadSuccess}
													width="150px"
													height="32px"
													emptyTips={`请上传${props.detail.svcType == "web" ? "web资源" : "服务程序"}`}
												></LazyUploadFile>
											</div>
										</el-form-item>
									)} */}
								{/* <el-form-item label="描述" prop="desc">
							<el-input v-model={props.detail.desc} placeholder="描述" auto-size type="textarea" rows={8} />
						</el-form-item> */}
							</el-form>
						</div>
						{props.detail.svcType != "docker" && (
							<el-form label-width="100">
								{/* <el-form-item label="应用运行系统" prop="architecture">
									<el-radio-group v-model={props.detail.architecture}>
										{typeList.value.map((dict: Dict) => {
											return <el-radio label={dict.key}>{dict.label}</el-radio>;
										})}
									</el-radio-group>
								</el-form-item> */}
							</el-form>
						)}
					</div>
				</DialogBox>
			);
		};
	}
});
